{% extends "pc/template.html" %}

{% block title %}
反馈列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<meta name="current-user" content="{{ request.session.user.id }}">
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .container-xxl {
        padding: 2rem 1.5rem;
    }
    
    .card {
        margin: 1rem 0;
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        transition: all 0.3s ease;
    }
    
    .card:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    
    .card-header {
        background: #fff;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        border-radius: 1rem 1rem 0 0 !important;
    }
    
    .card-header h5 {
        color: #566a7f;
        font-weight: 600;
        margin: 0;
    }
    
    .table-responsive {
        margin: 0;
        padding: 1rem;
    }
    
    .table {
        margin: 0;
    }
    
    .table thead th {
        background: #f8f9fa;
        color: #566a7f;
        font-weight: 600;
        border-bottom: 2px solid #e9ecef;
        padding: 1rem;
    }
    
    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
        color: #697a8d;
        border-bottom: 1px solid #e9ecef;
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
    }
    
    .table tbody tr {
        transition: all 0.2s ease;
    }
    
    .table tbody tr:hover {
        background: #f8f9fa;
    }
    
    .feedback-content {
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .feedback-images {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
    }
    
    .feedback-image {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 0.5rem;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .feedback-image:hover {
        transform: scale(1.1);
    }
    
    .status-badge {
        padding: 0.35rem 0.65rem;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
    }
    
    .status-pending {
        background: #fff3cd;
        color: #856404;
    }
    
    .status-replied {
        background: #d4edda;
        color: #155724;
    }
    
    .action-buttons .btn {
        padding: 0.4rem 0.6rem;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-buttons .btn:hover {
        transform: translateY(-2px);
    }
    
    .btn-info {
        background: #03c3ec;
        border-color: #03c3ec;
        color: #fff;
    }
    
    .btn-info:hover {
        background: #02a8c8;
        border-color: #02a8c8;
        color: #fff;
    }
    
    .btn-danger {
        background: #ff3e1d;
        border-color: #ff3e1d;
        color: #fff;
    }
    
    .btn-danger:hover {
        background: #e63617;
        border-color: #e63617;
        color: #fff;
    }
    
    /* 分页样式 */
    .pagination {
        margin: 1rem 0 0 0;
        justify-content: center;
    }
    
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        color: #566a7f;
        background-color: #fff;
        border: 1px solid #d9dee3;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
        color: #fff;
    }
    
    .pagination .page-link:hover {
        color: #696cff;
        background-color: #f5f5f9;
        border-color: #d9dee3;
        transform: translateY(-1px);
    }
    
    .pagination .page-item.disabled .page-link {
        color: #a3a4cc;
        pointer-events: none;
        background-color: #fff;
        border-color: #d9dee3;
    }
    
    /* 模态框美化 */
    .modal-content {
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    
    .modal-header {
        background: #f8f9fa;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        border-radius: 1rem 1rem 0 0;
    }
    
    .modal-title {
        color: #566a7f;
        font-weight: 600;
        font-size: 1.25rem;
    }
    
    .modal-body {
        padding: 1.5rem;
    }
    
    .modal-footer {
        background: #f8f9fa;
        border-top: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        border-radius: 0 0 1rem 1rem;
    }
    
    .form-label {
        color: #566a7f;
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control {
        border-radius: 0.5rem;
        border: 1px solid #d9dee3;
        padding: 0.5rem 1rem;
        transition: all 0.2s ease;
    }
    
    .form-control:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.2rem rgba(105, 108, 255, 0.25);
    }
    
    /* 下拉菜单样式 */
    .dropdown-menu {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        padding: 0.5rem;
        min-width: 160px;
    }
    
    .dropdown-item {
        padding: 0.6rem 1rem;
        color: #697a8d;
        border-radius: 0.4rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .dropdown-item:hover {
        background: #f8f9fa;
        color: #566a7f;
    }
    
    .dropdown-item i {
        font-size: 1.1rem;
    }
    
    .dropdown-item.view {
        color: #03c3ec;
    }
    
    .dropdown-item.reply {
        color: #ffab00;
    }
    
    .dropdown-item.delete {
        color: #ff3e1d;
    }
    
    .dropdown-item.view:hover {
        background: rgba(3, 195, 236, 0.1);
    }
    
    .dropdown-item.reply:hover {
        background: rgba(255, 171, 0, 0.1);
    }
    
    .dropdown-item.delete:hover {
        background: rgba(255, 62, 29, 0.1);
    }
    
    .dropdown-toggle::after {
        display: none;
    }
    
    .action-btn {
        background: #f8f9fa;
        border: 1px solid #d9dee3;
        color: #697a8d;
        padding: 0.4rem 0.8rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-btn:hover {
        background: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
    }
    
    .action-btn i {
        font-size: 1.1rem;
    }
    
    /* 图片上传区域美化 */
    .image-upload-area {
        border: 2px dashed #d9dee3;
        border-radius: 0.5rem;
        padding: 1.5rem;
        text-align: center;
        background: #f8f9fa;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    
    .image-upload-area:hover {
        border-color: #696cff;
        background: #f5f5f9;
    }
    
    .image-upload-area i {
        font-size: 2rem;
        color: #696cff;
        margin-bottom: 0.5rem;
    }
    
    .image-upload-area p {
        color: #697a8d;
        margin: 0;
    }
    
    /* 图片预览区域美化 */
    .image-preview-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
        gap: 1rem;
        margin-top: 1rem;
    }
    
    .image-preview-item {
        position: relative;
        aspect-ratio: 1;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .image-preview-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
    }
    
    .image-preview-item:hover img {
        transform: scale(1.1);
    }
    
    .image-preview-item .remove-btn {
        position: absolute;
        top: 0.25rem;
        right: 0.25rem;
        background: rgba(255, 255, 255, 0.9);
        border: none;
        border-radius: 50%;
        width: 1.5rem;
        height: 1.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .image-preview-item .remove-btn:hover {
        background: #ff3e1d;
        color: white;
    }
    
    /* 图片预览模态框美化 */
    .image-preview-modal .modal-dialog {
        max-width: 90%;
        margin: 1.75rem auto;
    }
    
    .image-preview-modal .modal-content {
        background: rgba(0, 0, 0, 0.9);
    }
    
    .image-preview-modal .modal-header {
        background: transparent;
        border-bottom: none;
        padding: 1rem;
    }
    
    .image-preview-modal .modal-title {
        color: white;
    }
    
    .image-preview-modal .btn-close {
        filter: brightness(0) invert(1);
    }
    
    .image-preview-modal .modal-body {
        padding: 0;
        text-align: center;
        position: relative;
    }
    
    .image-preview-modal img {
        max-width: 100%;
        max-height: 80vh;
        object-fit: contain;
    }

    .image-preview-nav {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 100%;
        display: flex;
        justify-content: space-between;
        padding: 0 1rem;
        pointer-events: none;
    }

    .image-preview-nav button {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        border-radius: 50%;
        width: 3rem;
        height: 3rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.5rem;
        cursor: pointer;
        transition: all 0.3s ease;
        pointer-events: auto;
    }

    .image-preview-nav button:hover {
        background: rgba(255, 255, 255, 0.3);
    }

    .image-preview-nav button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .image-preview-counter {
        position: absolute;
        bottom: 1rem;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 0.5rem 1rem;
        border-radius: 1rem;
        font-size: 0.875rem;
    }
    
    /* 反馈详情美化 */
    .feedback-detail-item {
        margin-bottom: 1.5rem;
        padding-bottom: 1.5rem;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }
    
    .feedback-detail-item:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }
    
    .feedback-detail-label {
        color: #566a7f;
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .feedback-detail-content {
        color: #697a8d;
        line-height: 1.5;
    }
    
    /* 回复表单美化 */
    .reply-form textarea {
        resize: none;
        min-height: 120px;
    }
    
    .reply-form .form-control:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.2rem rgba(105, 108, 255, 0.25);
    }
    
    /* 调整SweetAlert2的z-index */
    .swal2-container {
        z-index: 9999 !important;
    }
    
    .swal2-popup {
        z-index: 9999 !important;
    }
    
    .swal2-backdrop-show {
        z-index: 9998 !important;
    }
    
    /* 确保模态框的z-index低于SweetAlert2 */
    .modal {
        z-index: 1050;
    }
    
    .modal-backdrop {
        z-index: 1040;
    }

    /* 针对内容、用户、类型等字段单独设置最大宽度 */
    .td-limit-5 {
        max-width: 60px;
    }
    .td-limit-10 {
        max-width: 120px;
    }
    .td-tooltip {
        position: relative;
    }
    .td-tooltip:hover::after {
        content: attr(data-fulltext);
        position: absolute;
        left: 0;
        top: 100%;
        background: #333;
        color: #fff;
        padding: 4px 10px;
        border-radius: 4px;
        font-size: 13px;
        white-space: pre-line;
        z-index: 99;
        min-width: 80px;
        max-width: 300px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        margin-top: 2px;
    }

    @media (min-width: 768px) {
        #viewFeedbackModal .modal-body .row {
            min-height: 420px;
        }
        #viewFeedbackModal .modal-body .col-md-6 {
            border-right: 1px solid #f0f0f0;
        }
        #viewFeedbackModal .modal-body .col-md-6:last-child {
            border-right: none;
        }
    }
    #viewFeedbackModal .modal-body .col-md-6 {
        padding: 0 1.5rem;
    }
    #viewFeedbackModal .modal-body .reply-form {
        background: #f8f9fa;
        border-radius: 1rem;
        padding: 1.5rem 1rem;
        margin-top: 1rem;
    }
    #viewFeedbackModal .modal-body .reply-form textarea {
        min-height: 100px;
    }
    #viewFeedbackModal .modal-body .image-upload-area {
        margin-bottom: 0.5rem;
    }
    #viewFeedbackModal .modal-body .image-preview-container {
        margin-bottom: 0.5rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 反馈列表卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">反馈列表</h5>
            <div class="d-flex gap-2 align-items-center">
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                        状态筛选
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="filterByStatus('all')">全部</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="filterByStatus('待处理')">待处理</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" onclick="filterByStatus('已处理')">已处理</a></li>
                    </ul>
                </div>
                <div class="input-group" style="width: 300px;">
                    <input type="date" class="form-control" id="dateFilter" onchange="filterByDate(this.value)">
                    <button class="btn btn-outline-secondary" type="button" onclick="clearDateFilter()">
                        <i class="bx bx-x"></i>
                    </button>
                </div>
                <button type="button" class="btn btn-outline-secondary" onclick="resetFilter()">
                    重置筛选
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户</th>
                            <th>类型</th>
                            <th>内容</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="feedbackTableBody">
                        <!-- 反馈数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 查看反馈详情模态框 -->
    <div class="modal fade" id="viewFeedbackModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">反馈详情与回复</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <div class="row g-4 flex-md-row flex-column">
                    <!-- 左侧反馈内容 -->
                    <div class="col-md-6 col-12 border-end">
                    <div class="feedback-detail-item">
                        <div class="feedback-detail-label">反馈用户</div>
                        <div class="feedback-detail-content" id="feedbackDetailUser"></div>
                    </div>
                    <div class="feedback-detail-item">
                        <div class="feedback-detail-label">反馈类型</div>
                        <div class="feedback-detail-content" id="feedbackDetailType"></div>
                    </div>
                    <div class="feedback-detail-item">
                        <div class="feedback-detail-label">反馈内容</div>
                        <div class="feedback-detail-content" id="feedbackDetailContent"></div>
                    </div>
                    <div class="feedback-detail-item">
                        <div class="feedback-detail-label">反馈图片</div>
                        <div class="feedback-detail-content">
                            <div id="feedbackDetailImages" class="image-preview-container"></div>
                        </div>
                    </div>
                    <div class="feedback-detail-item">
                        <div class="feedback-detail-label">反馈状态</div>
                        <div class="feedback-detail-content" id="feedbackDetailStatus"></div>
                    </div>
                        <div class="feedback-detail-item">
                          <div class="feedback-detail-label">创建时间</div>
                          <div class="feedback-detail-content" id="feedbackDetailCreateTime"></div>
                        </div>
                        <div class="feedback-detail-item">
                          <div class="feedback-detail-label">更新时间</div>
                          <div class="feedback-detail-content" id="feedbackDetailUpdateTime"></div>
                            </div>
                        </div>
                    <!-- 右侧回复表单 -->
                    <div class="col-md-6 col-12">
                      <form id="replyFeedbackFormInDetail" class="reply-form">
                          <input type="hidden" id="replyFeedbackIdInDetail">
                          <div class="mb-4">
                              <label class="form-label" for="replyContentInDetail">回复内容</label>
                              <textarea class="form-control" id="replyContentInDetail" name="feedback_reply" rows="4" required></textarea>
                        </div>
                          <div class="mb-4">
                              <label class="form-label">回复图片</label>
                              <div class="image-upload-area" onclick="document.getElementById('replyImagesInDetail').click()">
                                  <i class="bx bx-cloud-upload"></i>
                                  <p>点击或拖拽图片到此处上传</p>
                                  <small class="text-muted">支持多张图片上传</small>
                        </div>
                              <input type="file" class="form-control" id="replyImagesInDetail" multiple accept="image/*" style="display: none;">
                              <div id="selectedImagesPreviewInDetail" class="image-preview-container mt-3"></div>
                    </div>
                          <div class="mb-4" id="replyInfoSectionInDetail" style="display:none;">
                              <label class="form-label">已回复内容</label>
                              <div class="feedback-detail-content" id="feedbackDetailReplyInDetail"></div>
                              <div class="feedback-detail-content" id="feedbackDetailReplyTimeInDetail"></div>
                              <div class="feedback-detail-content" id="feedbackDetailReplyUserInDetail"></div>
                              <div id="feedbackDetailReplyImagesInDetail" class="image-preview-container mt-2"></div>
                    </div>
                          <div class="d-flex justify-content-end">
                              <button type="button" class="btn btn-primary" onclick="submitReplyInDetail()">提交回复</button>
                          </div>
                      </form>
                    </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 回复反馈模态框 -->
    <div class="modal fade" id="replyFeedbackModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">回复反馈</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="replyFeedbackForm" class="reply-form">
                        <input type="hidden" id="replyFeedbackId">
                        <div class="mb-4">
                            <label class="form-label" for="replyContent">回复内容</label>
                            <textarea class="form-control" id="replyContent" name="feedback_reply" rows="4" required></textarea>
                        </div>
                        <div class="mb-4">
                            <label class="form-label">回复图片</label>
                            <div class="image-upload-area" onclick="document.getElementById('replyImages').click()">
                                <i class="bx bx-cloud-upload"></i>
                                <p>点击或拖拽图片到此处上传</p>
                                <small class="text-muted">支持多张图片上传</small>
                            </div>
                            <input type="file" class="form-control" id="replyImages" multiple accept="image/*" style="display: none;">
                            <div id="selectedImagesPreview" class="image-preview-container mt-3"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitReply()">提交回复</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div class="modal fade image-preview-modal" id="imagePreviewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">图片预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <img id="previewImage" src="" alt="预览图片">
                    <div class="image-preview-nav">
                        <button type="button" onclick="prevImage()" id="prevImageBtn">
                            <i class="bx bx-chevron-left"></i>
                        </button>
                        <button type="button" onclick="nextImage()" id="nextImageBtn">
                            <i class="bx bx-chevron-right"></i>
                        </button>
                    </div>
                    <div class="image-preview-counter" id="imageCounter"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 全局变量
    let allFeedbacks = []; // 存储所有反馈数据
    let filteredFeedbacks = []; // 存储筛选后的反馈数据
    let currentPage = 1; // 当前页码
    const itemsPerPage = 10; // 每页显示的数量
    let currentFilter = 'all'; // 当前筛选状态
    let currentDate = null; // 当前选择的日期

    // 全局变量用于存储当前预览的图片列表和索引
    let currentPreviewImages = [];
    let currentPreviewIndex = 0;

    // 页面加载完成后获取反馈列表
    document.addEventListener('DOMContentLoaded', function() {
        getFeedbackList();
        // 设置日期选择器的最大值为今天
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('dateFilter').max = today;
    });

    // 获取反馈列表
    function getFeedbackList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get('/api/feedback/get_feedback_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allFeedbacks = response.data.data;
                    filteredFeedbacks = [...allFeedbacks];
                    currentPage = 1; // 重置到第一页
                    renderFeedbackTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取反馈列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 按日期筛选
    function filterByDate(date) {
        currentDate = date;
        applyFilters();
    }

    // 清除日期筛选
    function clearDateFilter() {
        document.getElementById('dateFilter').value = '';
        currentDate = null;
        applyFilters();
    }

    // 应用所有筛选条件
    function applyFilters() {
        filteredFeedbacks = [...allFeedbacks];

        // 应用状态筛选
        if (currentFilter !== 'all') {
            filteredFeedbacks = filteredFeedbacks.filter(feedback => feedback.feedback_status === currentFilter);
        }

        // 应用日期筛选
        if (currentDate) {
            filteredFeedbacks = filteredFeedbacks.filter(feedback => {
                const feedbackDate = feedback.create_time.split(' ')[0];
                return feedbackDate === currentDate;
            });
        }

        currentPage = 1;
        renderFeedbackTable();
        renderPagination();
        updateFilterButtonState();
    }

    // 按状态筛选
    function filterByStatus(status) {
        currentFilter = status;
        applyFilters();
    }

    // 重置筛选
    function resetFilter() {
        currentFilter = 'all';
        currentDate = null;
        document.getElementById('dateFilter').value = '';
        filteredFeedbacks = [...allFeedbacks];
        currentPage = 1;
        renderFeedbackTable();
        renderPagination();
        updateFilterButtonState();
    }

    // 更新筛选按钮状态
    function updateFilterButtonState() {
        const statusButtons = document.querySelectorAll('.dropdown-item');
        statusButtons.forEach(button => {
            const status = button.getAttribute('onclick').match(/'([^']+)'/)[1];
            if (status === currentFilter) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });
    }

    // 渲染反馈表格
    function renderFeedbackTable() {
        const tbody = document.getElementById('feedbackTableBody');
        tbody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageFeedbacks = filteredFeedbacks.slice(startIndex, endIndex);

        if (currentPageFeedbacks.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-4">
                        <div class="text-muted">
                            <i class="bx bx-info-circle fs-4"></i>
                            <p class="mt-2 mb-0">暂无数据</p>
                        </div>
                    </td>
                </tr>
            `;
            return;
        }

        currentPageFeedbacks.forEach(feedback => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td class="td-limit-10 td-tooltip" data-fulltext="${feedback.feedback_id}">${feedback.feedback_id}</td>
                <td class="td-limit-5 td-tooltip" data-fulltext="${feedback.feedback_user}">${feedback.feedback_user}</td>
                <td class="td-limit-5 td-tooltip" data-fulltext="${feedback.feedback_type}">${feedback.feedback_type}</td>
                <td class="td-limit-10 td-tooltip" data-fulltext="${feedback.feedback_content}">${feedback.feedback_content}</td>
                <td>
                    <span class="status-badge ${feedback.feedback_status === '待处理' ? 'status-pending' : 'status-replied'}">
                        ${feedback.feedback_status}
                    </span>
                </td>
                <td>${feedback.create_time}</td>
                <td class="action-buttons">
                    <div class="dropdown">
                        <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-dots-vertical-rounded"></i>
                            <span>操作</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item view" href="javascript:void(0)" onclick="viewFeedback('${feedback.feedback_id}')">
                                    <i class="bx bx-show"></i>
                                    <span>查看</span>
                                </a>
                            </li>
                            ${feedback.feedback_status === '待处理' ? `
                                <li>
                                    <a class="dropdown-item reply" href="javascript:void(0)" onclick="showReplyModal('${feedback.feedback_id}')">
                                        <i class="bx bx-reply"></i>
                                        <span>回复</span>
                                    </a>
                                </li>
                            ` : ''}
                            <li>
                                <a class="dropdown-item delete" href="javascript:void(0)" onclick="deleteFeedback('${feedback.feedback_id}')">
                                    <i class="bx bx-trash"></i>
                                    <span>删除</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(filteredFeedbacks.length / itemsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > Math.ceil(filteredFeedbacks.length / itemsPerPage)) {
            return;
        }
        currentPage = page;
        renderFeedbackTable();
        renderPagination();
    }

    // 查看反馈详情（左右分栏）
    function viewFeedback(feedbackId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/feedback/get_feedback/${feedbackId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const feedback = response.data.data;
                    // 填充反馈详情（左侧）
                    document.getElementById('feedbackDetailUser').textContent = feedback.feedback_user;
                    document.getElementById('feedbackDetailType').textContent = feedback.feedback_type;
                    document.getElementById('feedbackDetailContent').textContent = feedback.feedback_content;
                    document.getElementById('feedbackDetailStatus').textContent = feedback.feedback_status;
                    document.getElementById('feedbackDetailCreateTime').textContent = feedback.create_time;
                    document.getElementById('feedbackDetailUpdateTime').textContent = feedback.update_time;
                    // 反馈图片
                    const imagesContainer = document.getElementById('feedbackDetailImages');
                    const feedbackImages = feedback.images.filter(image => image.image_type === 1);
                    if (feedbackImages.length > 0) {
                        imagesContainer.innerHTML = feedbackImages.map((image, index) => `
                            <div class="image-preview-item">
                                <img src="${image.image}" alt="反馈图片" onclick="previewFeedbackImages(${index})">
                            </div>
                        `).join('');
                        window.currentFeedbackImages = feedbackImages;
                    } else {
                        imagesContainer.innerHTML = '<p>暂无图片</p>';
                    }
                    // 右侧回复表单
                    document.getElementById('replyFeedbackIdInDetail').value = feedback.feedback_id;
                    document.getElementById('replyContentInDetail').value = '';
                    document.getElementById('replyImagesInDetail').value = '';
                    document.getElementById('selectedImagesPreviewInDetail').innerHTML = '';
                    // 如果已回复，显示已回复内容
                    if (feedback.feedback_status === '已处理') {
                        document.getElementById('replyInfoSectionInDetail').style.display = '';
                        document.getElementById('feedbackDetailReplyInDetail').textContent = feedback.feedback_reply || '暂无回复';
                        document.getElementById('feedbackDetailReplyTimeInDetail').textContent = feedback.feedback_reply_time ? '回复时间：' + feedback.feedback_reply_time : '';
                        document.getElementById('feedbackDetailReplyUserInDetail').textContent = feedback.feedback_reply_user ? '回复人：' + feedback.feedback_reply_user : '';
                        // 回复图片
                        const replyImagesContainer = document.getElementById('feedbackDetailReplyImagesInDetail');
                        const replyImages = feedback.images.filter(image => image.image_type === 2);
                        if (replyImages.length > 0) {
                            replyImagesContainer.innerHTML = replyImages.map((image, index) => `
                                <div class="image-preview-item">
                                    <img src="${image.image}" alt="回复图片" onclick="previewReplyImages(${index})">
                                </div>
                            `).join('');
                            window.currentReplyImages = replyImages;
                        } else {
                            replyImagesContainer.innerHTML = '<p>暂无图片</p>';
                        }
                    } else {
                        document.getElementById('replyInfoSectionInDetail').style.display = 'none';
                    }
                    const modal = new bootstrap.Modal(document.getElementById('viewFeedbackModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                Swal.fire('错误', '获取反馈详情失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 预览反馈图片
    function previewFeedbackImages(index) {
        if (!window.currentFeedbackImages) return;
        currentPreviewImages = window.currentFeedbackImages.map(img => img.image);
        currentPreviewIndex = index;
        updatePreviewImage();
        const modal = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
        modal.show();
    }

    // 预览回复图片
    function previewReplyImages(index) {
        if (!window.currentReplyImages) return;
        currentPreviewImages = window.currentReplyImages.map(img => img.image);
        currentPreviewIndex = index;
        updatePreviewImage();
        const modal = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
        modal.show();
    }

    // 更新预览图片
    function updatePreviewImage() {
        const previewImage = document.getElementById('previewImage');
        const prevBtn = document.getElementById('prevImageBtn');
        const nextBtn = document.getElementById('nextImageBtn');
        const counter = document.getElementById('imageCounter');

        if (!currentPreviewImages || currentPreviewImages.length === 0) return;

        previewImage.src = currentPreviewImages[currentPreviewIndex];
        
        // 更新按钮状态
        prevBtn.disabled = currentPreviewIndex === 0;
        nextBtn.disabled = currentPreviewIndex === currentPreviewImages.length - 1;
        
        // 更新计数器
        counter.textContent = `${currentPreviewIndex + 1} / ${currentPreviewImages.length}`;
    }

    // 上一张图片
    function prevImage() {
        if (currentPreviewIndex > 0) {
            currentPreviewIndex--;
            updatePreviewImage();
        }
    }

    // 下一张图片
    function nextImage() {
        if (currentPreviewIndex < currentPreviewImages.length - 1) {
            currentPreviewIndex++;
            updatePreviewImage();
        }
    }

    // 添加键盘事件监听
    document.addEventListener('keydown', function(e) {
        if (document.getElementById('imagePreviewModal').classList.contains('show')) {
            if (e.key === 'ArrowLeft') {
                prevImage();
            } else if (e.key === 'ArrowRight') {
                nextImage();
            }
        }
    });

    // 显示回复模态框
    function showReplyModal(feedbackId) {
        document.getElementById('replyFeedbackId').value = feedbackId;
        document.getElementById('replyContent').value = '';
        document.getElementById('replyImages').value = '';
        document.getElementById('selectedImagesPreview').innerHTML = '';
        const modal = new bootstrap.Modal(document.getElementById('replyFeedbackModal'));
        modal.show();
    }

    // 监听图片选择
    document.getElementById('replyImages').addEventListener('change', function(e) {
        const files = e.target.files;
        const preview = document.getElementById('selectedImagesPreview');
        
        preview.innerHTML = '';
        if (files.length > 0) {
            Array.from(files).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const div = document.createElement('div');
                    div.className = 'position-relative';
                    div.innerHTML = `
                        <img src="${e.target.result}" class="feedback-image" alt="预览图片">
                        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" 
                                onclick="this.parentElement.remove(); updateSelectedImagesCount();">
                            <i class="bx bx-x"></i>
                        </button>
                    `;
                    preview.appendChild(div);
                };
                reader.readAsDataURL(file);
            });
        } else {
            updateSelectedImagesCount();
        }
    });

    // 更新已选择图片数量
    function updateSelectedImagesCount() {
        const preview = document.getElementById('selectedImagesPreview');
        const images = preview.getElementsByTagName('img');
        const count = document.getElementById('selectedImagesCount');
        count.textContent = images.length > 0 ? `已选择 ${images.length} 张图片` : '';
    }

    // 提交回复
    function submitReply() {
        const feedbackId = document.getElementById('replyFeedbackId').value;
        const replyContent = document.getElementById('replyContent').value;

        if (!replyContent.trim()) {
            Swal.fire('错误', '请输入回复内容', 'error');
            return;
        }

        const loadingToast = Swal.fire({
            title: '提交中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const formData = new FormData();
        formData.append('feedback_reply', replyContent);
        formData.append('feedback_reply_user', document.querySelector('meta[name="current-user"]').getAttribute('content'));

        axios.post(`/api/feedback/update_feedback/${feedbackId}/`, formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 如果有图片，则上传图片
                    const imageFiles = document.getElementById('replyImages').files;
                    if (imageFiles.length > 0) {
                        uploadReplyImages(feedbackId, imageFiles);
                    } else {
                        Swal.fire({
                            icon: 'success',
                            title: '成功',
                            text: '回复提交成功',
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            const modal = bootstrap.Modal.getInstance(document.getElementById('replyFeedbackModal'));
                            modal.hide();
                            getFeedbackList();
                        });
                    }
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                Swal.fire('错误', '提交回复失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 上传回复图片
    function uploadReplyImages(feedbackId, imageFiles) {
        const loadingToast = Swal.fire({
            title: '上传图片中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const uploadPromises = Array.from(imageFiles).map(file => {
            const formData = new FormData();
            formData.append('image', file);
            formData.append('image_type', '2'); // 2表示回复图片
            return axios.post(`/api/feedback/upload_feedback_image/${feedbackId}/`, formData);
        });

        Promise.all(uploadPromises)
            .then(() => {
                Swal.fire({
                    icon: 'success',
                    title: '成功',
                    text: '回复和图片提交成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('replyFeedbackModal'));
                    modal.hide();
                    getFeedbackList();
                });
            })
            .catch(function(error) {
                console.error('Error:', error);
                Swal.fire('错误', '图片上传失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 删除反馈
    function deleteFeedback(feedbackId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这条反馈吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/feedback/delete_feedback/${feedbackId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '反馈删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getFeedbackList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除反馈失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }

    // 监听图片选择（详情右侧回复）
    document.getElementById('replyImagesInDetail').addEventListener('change', function(e) {
        const files = e.target.files;
        const preview = document.getElementById('selectedImagesPreviewInDetail');
        preview.innerHTML = '';
        if (files.length > 0) {
            Array.from(files).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const div = document.createElement('div');
                    div.className = 'position-relative';
                    div.innerHTML = `
                        <img src="${e.target.result}" class="feedback-image" alt="预览图片">
                        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" 
                                onclick="this.parentElement.remove();">
                            <i class="bx bx-x"></i>
                        </button>
                    `;
                    preview.appendChild(div);
                };
                reader.readAsDataURL(file);
            });
        }
    });

    // 详情弹窗右侧提交回复
    function submitReplyInDetail() {
        const feedbackId = document.getElementById('replyFeedbackIdInDetail').value;
        const replyContent = document.getElementById('replyContentInDetail').value;
        if (!replyContent.trim()) {
            Swal.fire('错误', '请输入回复内容', 'error');
            return;
        }
        const loadingToast = Swal.fire({
            title: '提交中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        const formData = new FormData();
        formData.append('feedback_reply', replyContent);
        formData.append('feedback_reply_user', document.querySelector('meta[name="current-user"]').getAttribute('content'));
        axios.post(`/api/feedback/update_feedback/${feedbackId}/`, formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 如果有图片，则上传图片
                    const imageFiles = document.getElementById('replyImagesInDetail').files;
                    if (imageFiles.length > 0) {
                        uploadReplyImagesInDetail(feedbackId, imageFiles);
                    } else {
                        Swal.fire({
                            icon: 'success',
                            title: '成功',
                            text: '回复提交成功',
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            getFeedbackList();
                            viewFeedback(feedbackId); // 刷新详情
                        });
                    }
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                Swal.fire('错误', '提交回复失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 上传回复图片（详情右侧）
    function uploadReplyImagesInDetail(feedbackId, imageFiles) {
        const loadingToast = Swal.fire({
            title: '上传图片中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        const uploadPromises = Array.from(imageFiles).map(file => {
            const formData = new FormData();
            formData.append('image', file);
            formData.append('image_type', '2'); // 2表示回复图片
            return axios.post(`/api/feedback/upload_feedback_image/${feedbackId}/`, formData);
        });
        Promise.all(uploadPromises)
            .then(() => {
                Swal.fire({
                    icon: 'success',
                    title: '成功',
                    text: '回复和图片提交成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    getFeedbackList();
                    viewFeedback(feedbackId); // 刷新详情
                });
            })
            .catch(function(error) {
                console.error('Error:', error);
                Swal.fire('错误', '图片上传失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
        });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}